<template>
  <SelectUser :isRadio="selectOptions.isRadio" :isNeedSearch="selectOptions.isNeedSearch" :title="selectOptions.title"
    :userList="userList" @search="handleSearch" @complete="handleSelectedResult" />
</template>
<script lang="ts" setup>
import {
  TUIFriendService,
  TUIStore,
  StoreName,
  TUITranslateService,
} from '@tencentcloud/chat-uikit-engine';
import { ref, watchEffect } from '../../../adapter-vue';
import { Toast, TOAST_TYPE } from '../../common/Toast/index';
import TUICore from '@tencentcloud/tui-core';
import SelectUser from '../../common/SelectUser/index.vue';
import Server from '../server';
const TUIContactServer = Server.getInstance();
const TUIConstants = TUIContactServer.constants;

const needSearch = ref(false);
const friendList = ref([]);
const userList = ref([]);
const TUISearchServer = ref<any>(null);
const selectOptions = ref({
  isRadio: false,
  isNeedSearch: false,
  title: '',
});

const generateSearchServer = (isNeedSearch: any) => {
  TUISearchServer.value = TUICore.getService(TUIConstants.TUISearch.SERVICE.NAME);
  if (TUISearchServer.value) {
    needSearch.value = isNeedSearch;
  } else {
    console.warn('请添加 TUISearch 组件');
  }
};

watchEffect(() => {
  const params = TUIContactServer.getOnCallParams(TUIConstants.TUIContact.SERVICE.METHOD.SELECT_FRIEND);
  selectOptions.value.title = params.title;
  selectOptions.value.isRadio = params.isRadio;
  selectOptions.value.isNeedSearch = params.isNeedSearch;
  if (params.isNeedSearch) {
    generateSearchServer(params.isNeedSearch);
  }
  TUIFriendService.getFriendList().then((res: any) => {
    friendList.value = res.data.map((item: any) => item.profile);
    userList.value = friendList.value;
  }).catch((err: any) => {
    console.warn('getFriendList error:', err);
  });
});

const handleSelectedResult = (memberList: Array<any>) => {
  TUIStore.update(StoreName.CUSTOM, 'isShowSelectFriendComponent', false);
  const callback = TUIContactServer.getOnCallCallback(TUIConstants.TUIContact.SERVICE.METHOD.SELECT_FRIEND);
  callback && callback(memberList);
};

const searchFail = () => {
  Toast({
    message: TUITranslateService.t('TUIGroup.该用户不存在'),
    type: TOAST_TYPE.ERROR,
  });
  userList.value = [...friendList.value];
};

const handleSearch = async (val: string) => {
  if (!val) {
    // return userList.value = friendList.value;
    return userList.value = []
  }

  try {
    // 获取认证令牌
    const token = localStorage.getItem('token'); // 或者从您的认证服务获取令牌

    // 调用后端API，包含认证令牌
    const response = await fetch(`/api/tencent-im/search-users?keyword=${encodeURIComponent(val)}`, {
      headers: {
        'Authorization': `Bearer ${token}` // 添加认证头
      }
    });

    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status}`);
    }

    const result = await response.json();
    if (result.code!=200 || !result.data || result.data.length === 0) {
      userList.value = [];
      return searchFail();
    }

    // 将后端搜索结果转换为前端需要的格式
    const users = result.data.map((user: any) => ({
      userID: user.tencentUserId || user.userID, // 腾讯云IM的userID
      nick: user.nick || user.nickname || user.username || `用户${user.id}`,
      avatar: user.avatar || 'https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png'
    }));
   

    userList.value = users;

    // 检查搜索结果中的用户是否已在好友列表中
    const newUsers = users.filter((user: any) =>
      !friendList.value.some((friend: any) => friend.userID === user.userID)
    );

    // 如果有新用户，将其添加到好友列表中
    if (newUsers.length > 0) {
      friendList.value = [...friendList.value, ...newUsers];
    }

  } catch (error) {
    console.error('搜索用户失败:', error);
    return searchFail();
  }
};
</script>
